import 'dart:async';

import 'package:flutter/material.dart';
import 'package:xsdk_flutter/xsdk/framework/base/xsdk_function.dart';
import 'package:xsdk_flutter/xsdk/framework/base/xsdk_widget_stateful.dart';
import 'package:xsdk_flutter/xsdk/operation/x_constant_temp.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_notify_state_change.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_string.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_style.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_widget.dart';


class XButtonTimeState extends XState {

  int timeout_s;
  String? defaultName;
  
  Color defaultBackgroundColor;
  Color? timerBackgroundColor;
  Color? borderColor;
  
  bool isCircle=false;
  double topLeftRadius=5;
  double topRightRadius=5;
  double bottomLeftRadius=5;
  double bottomRightRadius=5;

  double? width;
  double? height;
  EdgeInsets? margin;
  EdgeInsets? padding;


  Timer? _timer;
  late int _times;
  late String _timeName;
  bool _isClick = false;

  FontWeight? fontWeight;
  Color? fontColor;
  double? fontSize;
  double? borderWidth;

  //是否自动开始
  bool isAutoStart=false;

  XFunctionEventNotify? onTimerComplete;
  XFunctionEventNotify? onClick;

  String? tag_action_receive_notify;
  XFunctionNotifyStateChangeListener? _listener_receive_notify;

  XButtonTimeState(
      {
        required this.timeout_s,
        this.defaultName,
        required this.defaultBackgroundColor,
        this.timerBackgroundColor, //Colors.grey.withOpacity(0.2)
        this.width,
        this.height,
        this.margin,
        this.padding,
        this.borderColor,
        this.borderWidth,
        this.isCircle=false,
        this.topLeftRadius=5,
        this.topRightRadius=5,
        this.bottomLeftRadius=5,
        this.bottomRightRadius=5,
        this.fontWeight,
        this.fontColor,
        this.fontSize,
        this.isAutoStart=false,
        this.onTimerComplete,
        this.onClick,
        this.tag_action_receive_notify
      }
      );


  @override
  void onCreate() {
    _initData();

    if(!XStringUtils.isEmpty(tag_action_receive_notify)){

      _listener_receive_notify=(String key,dynamic value){
        if(key=='restartTimer'){
          //重新开始计时
          restartTimer();
        }else if(key=='stopTimer'){
          //停止计数
          setState(() {
            _cancelTimer();
          });

        }
      };

      XNotifyStateChangeUtils.receiveChangeNotify(
          action: tag_action_receive_notify!,
          listener: _listener_receive_notify!
      );

    }

  }

  @override
  void onStart() {
  }

  @override
  Widget onBuild(BuildContext context) {

    return XWidgetUtils.getWidgetGestureDetector(
        onTap: (){

          if (!_isClick) {
            _isClick = true;
            if(onClick!=null){
              onClick!('1');
            }
            _startTimer();
          }else{
            if(onClick!=null){
              onClick!('0');
            }
          }
        },
        child: XWidgetUtils.getLayoutContainer(
            padding: padding,
            margin: margin,
            width: width,
            height: height,
            alignment: Alignment.center,
            decoration: XWidgetUtils.getBoxDecoration(
                backgroundColor: _isClick?(timerBackgroundColor??defaultBackgroundColor):defaultBackgroundColor,
                border:borderColor!=null?Border.all(color:borderColor!, style: BorderStyle.solid, width:borderWidth??XTempData.defaultDividerHeight):null,
                isCircle:isCircle,
                borderRadius: isCircle?null:BorderRadius.only(
                  topLeft: Radius.circular(topLeftRadius),
                  topRight: Radius.circular(topRightRadius),
                  bottomLeft: Radius.circular(bottomLeftRadius),
                  bottomRight: Radius.circular(bottomRightRadius),
                )
            ),
            child:XWidgetUtils.getWidgetText(
                _timeName,
                style: XStyleUtils.getTextStyle(
                  fontSize: fontSize??XTempData.defaultButtonFontSize,
                  color: fontColor??Colors.black,
                  fontWeight: fontWeight??FontWeight.normal,
                )
            )
        )
    );

  }


  @override
  void onStop() {
  }

  @override
  void onDestroy() {
    if(!XStringUtils.isEmpty(tag_action_receive_notify)){
      XNotifyStateChangeUtils.unReceiveChangeNotify(
          action: tag_action_receive_notify!,
          listener: _listener_receive_notify
      );
    }
    _cancelTimer();
  }



  @override
  Future<void> updateData({int pageIndex = 1}) async {
    if(isAutoStart){
      //自动开始倒数
      if (!_isClick) {
        _isClick = true;
        _startTimer();
      }
    }
  }

  //重新开始计时
  void restartTimer(){
    _cancelTimer();
    _startTimer();
  }


  ////////////////////////////////////////////////////////////////////

  void _initData(){
    _times = timeout_s;
    _timeName = XStringUtils.isEmpty(defaultName)?'${_times}s':defaultName!;
  }

  _startTimer() {
    _timer ??= Timer.periodic(const Duration(seconds: 1), (timer) {
      setState(() {
        _times--;
        _timeName = XStringUtils.isEmpty(defaultName)?'${_times}s':'$defaultName (${_times}s)';

        if (_times <= 0) {
          _cancelTimer();
          if(onTimerComplete!=null){
            onTimerComplete!('ok');
          }
        }
      });
    });
  }

  _cancelTimer() {
    _timer?.cancel();
    _timer = null;
    _isClick = false;
    //
    _initData();
  }

}